<style>
  .product-name {
    font-weight: bold;
  }

  .check-out {
    float: right;
    margin: 20px;
  }

  .total {
    font-weight: bold;
    font-size: x-large;
    margin-right: 20px;
    color: #2d8cf0;
  }
</style>

<template>
  <div>
    <Layout ref="layout">
      <span slot="breadcrumb">购物车</span>
      <Table size="large"
             :columns="columns"
             :data="cartItems"
             :stripe="true"
             @on-select="onSelect"
             @on-select-cancel="onSelectCancel"
             @on-selection-change="onSelectionChange">
      </Table>
      <div class="check-out">
        <span class="total">合计: {{total | currency}}</span>
        <Button size="large" shape="circle" type="primary" icon="checkmark">结算</Button>
      </div>
      <Modal
        v-model="confirm"
        @on-ok="remove"
        @on-cancel="deleteIndex = -1">
        <p slot="header" style="color:#f60;text-align:center">
          <Icon type="information-circled"></Icon>
          <span>删除确认</span>
        </p>
        <div style="text-align:center">
          <p>是否删除此项商品？</p>
        </div>
      </Modal>
    </Layout>
  </div>
</template>

<script type="text/ecmascript-6">
  import Layout from '@/components/Layout.vue'
  import EditNumber from '@/components/EditNumber.vue'
  import axios from 'axios'
  import {currency} from './../utils/currency'

  export default {
    data() {
      var self = this;
      return {
        columns: [
          {
            type: 'selection',
            width: 60,
            align: 'center'
          },
          {
            title: ' ',
            key: 'img',
            align: 'center',
            width: 200,
            render: (h, params) => {
              return h('img', {
                attrs: {
                  src: params.row.productImage
                },
                style: {
                  width: '70%',
                  maxWidth: '150px',
                  margin: '10px'
                }
              });
            }
          },
          {
            title: '商品',
            key: 'productName',
            align: 'left',
            width: 200,
            className: 'product-name'
          },
          {
            title: '价格',
            key: 'salePrice',
            align: 'center',
            render: (h, params) => {
              return h('div', {}, currency(params.row.salePrice));
            }
          },
          {
            title: '数量',
            key: 'productNum',
            align: 'center',
            render: (h, params) => {
              return h(EditNumber, {
                props: {
                  value: params.row.productNum
                },
                style: {
                  margin: '20px auto',
                  maxWidth: '150px'
                },
                on: {
                  'button-click': (value) => {
                    this.productNumEdit(params.index, value);
                  }
                }
              });
            }
          },
          {
            title: '总价',
            key: 'subtotal',
            align: 'center',
            render: (h, params) => {
              return h('div', {
                style: {
                  color: '#2d8cf0'
                },
              }, currency(params.row.subtotal));
            }
          },
          {
            title: '操作',
            key: 'edit',
            align: 'center',
            render: (h, params) => {
              return h('Button', {
                props: {
                  icon: 'ios-trash'
                },
                on: {
                  click: () => {
                    this.removeConfirm(params.index);
                  }
                }
              }, '删除');
            }
          }
        ],
        cartItems: [],
        confirm: false,
        deleteIndex: -1
      }
    },
    computed: {
      total() {
        let total = 0;
        this.cartItems.forEach((item) => {
          total += item.subtotal;
        });
        return total;
      }
    },
    components: {
      Layout,
      EditNumber
    },
    mounted() {
      this.init();
    },
    methods: {
      init() {
        this.$Loading.start();
        axios.get("/user/cart", {
          headers: {
            Authorization: this.$store.state.token
          }
        }).then((result) => {
          this.$Loading.finish();
          let res = result.data;
          let cartItems = [];
          if (res.code === 200) {
            res.data.forEach((item) => {
              let cartItem = {};
              cartItem.productId = item.good.productId;
              cartItem.productName = item.good.productName;
              cartItem.productImage = '/static/' + item.good.productImage;
              cartItem.salePrice = item.good.salePrice;
              cartItem._checked = item.checked === 1 ? true : false;
              cartItem.productNum = item.productNum;
              cartItem.subtotal = cartItem.salePrice * cartItem.productNum;
              cartItems.push(cartItem);
            });
            this.cartItems = cartItems;
          }
          else {
            this.cartItems = [];
          }
        });
      },
      productNumEdit(index, value) {
        let params = {
          action: 'num',
          value: value
        };
        axios.put(
          "/user/cart/" + this.cartItems[index].productId, null,
          {
            headers: {
              Authorization: this.$store.state.token,
            },
            params: params
          }
        ).then((result) => {
          let res = result.data;
          if (res.code === 200) {
            this.cartItems[index].productNum = value;
            this.cartItems[index].subtotal = this.cartItems[index].productNum * this.cartItems[index].salePrice;
          }
        });
      },
      remove() {
        axios.delete(
          "/user/cart/" + this.cartItems[this.deleteIndex].productId,
          {
            headers: {
              Authorization: this.$store.state.token
            }
          }
        ).then((result) => {
          let res = result.data;
          if (res.code === 200) {
            this.cartItems.splice(this.deleteIndex, 1);
          }
        });
      },
      removeConfirm(index) {
        this.deleteIndex = index;
        this.confirm = true;
      },
      onSelect(selection, row) {
        let params = {
          action: 'checked',
          value: 1
        };
        axios.put(
          "/user/cart/" + row.productId, null,
          {
            headers: {
              Authorization: this.$store.state.token,
            },
            params: params
          }
        ).then((result) => {
          let res = result.data;
          if (res.code === 200) {
            this.cartItems.forEach((item) => {
              if (item.productId === row.productId) {
                item._checked = true;
              }
            });
          }
        });
      },
      onSelectCancel(selection, row) {
        let params = {
          action: 'checked',
          value: 0
        };
        axios.put(
          "/user/cart/" + row.productId, null,
          {
            headers: {
              Authorization: this.$store.state.token,
            },
            params: params
          }
        ).then((result) => {
          let res = result.data;
          if (res.code === 200) {
            this.cartItems.forEach((item) => {
              if (item.productId === row.productId) {
                item._checked = false;
              }
            });
          }
        });
      },
      onSelectionChange(selection) {
        if (selection.length === 0) {
          let params = {
            checked: 0
          };
          axios.put(
            "/user/cart", null,
            {
              headers: {
                Authorization: this.$store.state.token,
              },
              params: params
            }
          ).then((result) => {
            let res = result.data;
            if (res.code === 200) {
              this.cartItems.forEach((item) => {
                item._checked = false;
              });
            }
          });
        } else if (selection.length === this.cartItems.length) {
          let params = {
            checked: 1
          };
          axios.put(
            "/user/cart", null,
            {
              headers: {
                Authorization: this.$store.state.token,
              },
              params: params
            }
          ).then((result) => {
            let res = result.data;
            if (res.code === 200) {
              this.cartItems.forEach((item) => {
                item._checked = true;
              });
            }
          });
        }
      }
    }
  }
</script>
